import { createStore, Store, useStore as vuexUseStore } from 'vuex';
import { IRootState, IStoreType } from './types';
import { getTableData } from '@/service/system/user';
import login from './login/login';
import system from './system/user';
import dashboard from './analysis/dashboard';

const store = createStore<IRootState>({
  state: () => {
    return {
      name: 'codewhy',
      age: 15,
      entireDepartment: [],
      entireRole: [],
      entireMenu: []
    };
  },

  mutations: {
    saveDepartmentList(state, playload) {
      state.entireDepartment = playload;
    },
    saveRoleList(state, playload) {
      state.entireRole = playload;
    },
    saveMenuList(state, playload) {
      state.entireMenu = playload;
    }
  },
  actions: {
    async getDepartmentList({ commit, dispatch }) {
      const res = await getTableData('/department/list', {
        offset: 0,
        size: 999
      });
      if (res.code === 1) {
        commit('saveDepartmentList', res.data.list);
        dispatch('getRoleList');
      }
    },
    async getRoleList({ commit, dispatch }) {
      const res = await getTableData('/role/list', {
        offset: 0,
        size: 999
      });
      if (res.code === 1) {
        commit('saveRoleList', res.data.list);
        dispatch('getMenuList');
      }
    },
    async getMenuList({ commit }) {
      const res = await getTableData('/menu/list');
      if (res.code === 1) {
        commit('saveMenuList', res.data.list);
      }
    }
  },
  modules: {
    login,
    system,
    dashboard
  }
});

export function useStore(): Store<IStoreType> {
  return vuexUseStore();
}
export default store;
